<template>
  <view class="contact-popup" v-if="visible">
    <view class="popup-mask" @tap="cancel"></view>
    <view class="popup-content">
      <view class="popup-header">
        <view class="popup-left" @tap="cancel">
          <text>取消</text>
        </view>
        <view class="popup-title">{{ title }}</view>
        <view class="popup-right" @tap="confirm">
          <text class="confirm-btn">完成</text>
        </view>
      </view>
      
      <!-- 添加搜索框 -->
      <view class="search-box">
        <view class="search-input-box">
          <uni-icons type="search" size="16" color="#999"></uni-icons>
          <input 
            class="search-input" 
            v-model="searchKeyword" 
            placeholder="搜索联系人" 
            confirm-type="search"
            @input="handleSearch"
          />
          <uni-icons v-if="searchKeyword" type="clear" size="16" color="#999" @click="clearSearch"></uni-icons>
        </view>
      </view>
      
      <view class="filter-tabs" v-if="filterTabs.length > 0">
        <view 
          class="filter-tab" 
          v-for="(tab, index) in filterTabs" 
          :key="index"
          :class="{ active: currentFilterTab === index }"
          @tap="switchFilterTab(index)"
        >
          {{ tab }}
        </view>
      </view>
      
      <!-- 添加加载状态 -->
      <view class="loading-container" v-if="loading">
        <uni-icons type="spinner-cycle" size="24" color="#007AFF"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view class="contacts-list" v-else>
        <view 
          class="contact-item" 
          v-for="(contact, index) in filteredContacts" 
          :key="contact.id"
          @tap="toggleContactSelection(contact)"
        >
          <view class="contact-avatar">
            <image v-if="contact.avatar" class="avatar" :src="contact.avatar" mode="aspectFill"></image>
            <view v-else class="avatar-placeholder">
              <text>{{ getNameInitial(contact.name) }}</text>
            </view>
          </view>
          <view class="contact-info">
            <text class="contact-name">{{ contact.name }}</text>
            <text v-if="contact.phone" class="contact-phone">{{ contact.phone }}</text>
          </view>
          <view class="contact-checkbox" :class="{ selected: isContactSelected(contact) }">
            <uni-icons v-if="isContactSelected(contact)" type="checkmarkempty" size="20" color="#fff"></uni-icons>
          </view>
        </view>
        
        <!-- 无数据提示 -->
        <view class="empty-tip" v-if="filteredContacts.length === 0">
          <text>暂无联系人</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import ContactApi from '@/sheep/api/contact/contact';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择人物'
  },
  contacts: {
    type: Array,
    default: () => []
  },
  filterTabs: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:visible', 'update:modelValue', 'confirm', 'cancel']);

const currentFilterTab = ref(0);
const selectedContacts = ref([]);
const searchKeyword = ref('');
const loading = ref(false);
const contactsList = ref([]);

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal === null || newVal === undefined) {
      selectedContacts.value = [];
    } else if (Array.isArray(newVal)) {
      selectedContacts.value = [...newVal];
    } else {
      // If it's a single value (not an array), wrap it in an array
      selectedContacts.value = [newVal];
    }
  },
  { immediate: true }
);

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    selectedContacts.value = [...props.modelValue];
    // 当弹窗显示时，加载联系人数据
    fetchContacts();
  }
}, { immediate: true });

// 根据当前选中的筛选标签和搜索关键词过滤联系人
const filteredContacts = computed(() => {
  let result = contactsList.value.length > 0 ? contactsList.value : props.contacts;
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    result = result.filter(contact => 
      (contact.name && contact.name.toLowerCase().includes(searchKeyword.value.toLowerCase())) || 
      (contact.phone && contact.phone.includes(searchKeyword.value))
    );
  }
  
  // 根据分组过滤
  if (currentFilterTab.value !== 0 && props.filterTabs.length > 0) {
    const groupName = props.filterTabs[currentFilterTab.value];
    result = result.filter(contact => contact.group === groupName);
  }
  
  return result;
});

// 获取姓名首字母
const getNameInitial = (name) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 切换筛选标签
const switchFilterTab = (index) => {
  currentFilterTab.value = index;
};

// 切换联系人选择状态
const toggleContactSelection = (contact) => {
  if (!props.multiple) {
    // 单选模式
    selectedContacts.value = [contact];
  } else {
    // 多选模式
    const index = selectedContacts.value.findIndex(item => item.id === contact.id);
    if (index === -1) {
      selectedContacts.value.push(contact);
    } else {
      selectedContacts.value.splice(index, 1);
    }
  }
};

// 检查联系人是否被选中
const isContactSelected = (contact) => {
  return selectedContacts.value.some(item => item.id === contact.id);
};

// 确认联系人选择
const confirm = () => {
  emit('update:modelValue', [...selectedContacts.value]);
  emit('confirm', [...selectedContacts.value]);
  emit('update:visible', false);
};

// 取消选择
const cancel = () => {
  emit('cancel');
  emit('update:visible', false);
};

// 处理搜索输入
const handleSearch = () => {
  // 如果联系人列表数量未超过200条，则直接在本地搜索
  if (contactsList.value.length > 0 && contactsList.value.length <= 200) {
    // 不调用接口，直接使用本地过滤
    return;
  }
  
  // 联系人数量超过200条或者还未加载联系人，则调用接口搜索
  if (searchKeyword.value.length > 0) {
    // 如果是纯数字，可能是在搜索电话号码，直接调用接口
    if (/^\d+$/.test(searchKeyword.value)) {
      fetchContacts(searchKeyword.value);
    } else {
      // 如果不是纯数字，可能是在搜索名称，先在本地过滤
      // 如果本地过滤结果为空，再调用接口
      const localFiltered = contactsList.value.filter(contact => 
        (contact.name && contact.name.toLowerCase().includes(searchKeyword.value.toLowerCase())) || 
        (contact.phone && contact.phone.includes(searchKeyword.value))
      );
      
      if (localFiltered.length === 0 || contactsList.value.length === 0) {
        fetchContacts(searchKeyword.value);
      }
    }
  }
};

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  
  // 如果联系人列表数量超过200条，则重新获取全部联系人
  if (contactsList.value.length > 200) {
    fetchContacts();
  }
};

// 获取联系人列表
const fetchContacts = async (keyword = '') => {
  loading.value = true;
  try {
    // 调用查询联系人接口，使用正确的参数格式
    const res = await ContactApi.queryContacts({
      searchContent: keyword
    });
    
    if (res.code === 0 && res.data) {
      contactsList.value = res.data.map(item => ({
        id: item.id,
        name: item.name || '未命名',
        avatar: item.avatarUrl || item.img,
        companyName: item.companyName || '',
        phone: item.phoneNumber || '',
        email: item.email || '',
        homeAddress: item.homeAddress || '',
        workAddress: item.workAddress || '',
        work: item.work || '',
        remark: item.remark || '',
        school: item.school || ''
      }));
    } else {
      // 如果API调用失败，使用本地存储的联系人数据
      const contacts = uni.getStorageSync('contactList') || [];
      contactsList.value = contacts.map(item => ({
        id: item.id,
        name: item.name,
        avatar: item.img,
        group: item.groupName || '',
        companyName: item.companyName || '',
        phone: item.phoneNumber || '',
        email: item.email || '',
        homeAddress: item.homeAddress || '',
        workAddress: item.workAddress || '',
        work: item.work || '',
        remark: item.remark || '',
        school: item.school || ''
      }));
    }
  } catch (error) {
    console.error('获取联系人失败:', error);
    // 如果API调用失败，使用本地存储的联系人数据
    const contacts = uni.getStorageSync('contactList') || [];
    contactsList.value = contacts.map(item => ({
      id: item.id,
      name: item.name,
      avatar: item.img,
      companyName: item.companyName || '',
      phone: item.phoneNumber || '',
      email: item.email || '',
      homeAddress: item.homeAddress || '',
      workAddress: item.workAddress || '',
      work: item.work || '',
      remark: item.remark || '',
      school: item.school || ''
    }));
    
    uni.showToast({
      title: '获取联系人失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取联系人列表
onMounted(() => {
  if (props.visible) {
    fetchContacts();
  }
});
</script>

<style lang="scss" scoped>
.contact-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-left, .popup-right {
  min-width: 120rpx;
}

.popup-left {
  color: #333;
  font-size: 28rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.popup-right {
  text-align: right;
}

.confirm-btn {
  color: #007AFF;
  font-size: 28rpx;
}

/* 添加搜索框样式 */
.search-box {
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-input-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
}

.filter-tabs {
  display: flex;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
  overflow-x: auto;
}

.filter-tab {
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  white-space: nowrap;
}

.filter-tab.active {
  color: #fff;
  background-color: #007AFF;
}

/* 添加加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.contacts-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 0;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  position: relative;
}

.contact-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  overflow: hidden;
  margin-right: 20rpx;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FF6B6B;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.contact-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.contact-name {
  font-size: 28rpx;
  color: #333;
}

.contact-phone {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.contact-checkbox {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-checkbox.selected {
  background-color: #007AFF;
  border-color: #007AFF;
}

/* 添加空数据提示样式 */
.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>